import { useMemo } from 'react';
import { useTheme } from './themeContext';
import { 
  baseColors, 
  biScreenColors, 
  chartColors, 
  componentStyles, 
  animations,
  getGradientColor,
  getChartColor,
  getStatusColor,
  getRankingColor,
  dataScreenStyles,
  getDataScreenTableClass,
  getDataScreenButtonClass,
  getDataScreenAnimationClass,
  getDataScreenTextSize
} from './theme';

// 主题颜色hooks
export const useThemeColors = () => {
  const { themeMode } = useTheme();
  
  // 根据主题模式返回相应的颜色
  const colors = useMemo(() => {
    const isDark = themeMode === 'dark';
    
    return {
      // 基础色彩
      base: baseColors,
      
      // BI大屏配色
      bi: biScreenColors,
      
      // 图表配色
      charts: chartColors,
      
      // 组件样式
      components: componentStyles,
      
      // 动画配置
      animations,
      
      // 自适应颜色（根据主题模式）
      adaptive: {
        background: isDark ? biScreenColors.background : baseColors.white,
        text: isDark ? biScreenColors.text.primary : baseColors.black,
        cardBg: isDark ? biScreenColors.cardBg : baseColors.white,
        border: isDark ? biScreenColors.border.primary : baseColors.gray[200],
      },
      
      // 工具函数
      utils: {
        getGradientColor,
        getChartColor,
        getStatusColor,
        getRankingColor,
        
        // 获取透明度变化的颜色
        withOpacity: (color: string, opacity: number) => {
          if (color.includes('rgba')) {
            return color.replace(/[\d\.]+\)$/g, `${opacity})`);
          }
          if (color.startsWith('#')) {
            const r = parseInt(color.slice(1, 3), 16);
            const g = parseInt(color.slice(3, 5), 16);
            const b = parseInt(color.slice(5, 7), 16);
            return `rgba(${r}, ${g}, ${b}, ${opacity})`;
          }
          return color;
        },
        
        // 生成渐变背景
        createGradient: (angle: number = 45, ...colors: string[]) => {
          return `linear-gradient(${angle}deg, ${colors.join(', ')})`;
        }
      }
    };
  }, [themeMode]);
  
  return colors;
};

// BI大屏专用hooks
export const useBIColors = () => {
  const colors = useThemeColors();
  
  return {
    // 快速访问BI配色
    primary: colors.bi.primary,
    secondary: colors.bi.secondary,
    background: colors.bi.background,
    cardBg: colors.bi.cardBg,
    text: colors.bi.text,
    border: colors.bi.border,
    
    // 快速获取渐变色
    gradient: (index: number) => getGradientColor(index),
    
    // 快速获取排行榜色
    ranking: (rank: number) => getRankingColor(rank),
    
    // 快速获取状态色
    status: (status: keyof typeof chartColors.status) => chartColors.status[status],
    
    // 卡片样式生成器
    cardStyle: (hover = true) => ({
      backgroundColor: colors.bi.cardBg,
      border: `1px solid ${colors.bi.border.muted}`,
      borderRadius: colors.components.card.borderRadius,
      boxShadow: colors.components.card.boxShadow,
      transition: hover ? colors.animations.hover.transition : 'none',
      ':hover': hover ? {
        backgroundColor: colors.bi.hoverBg,
        transform: colors.animations.hover.transform,
        boxShadow: colors.animations.hover.boxShadow
      } : undefined
    }),
    
    // 按钮样式生成器
    buttonStyle: (type: 'primary' | 'secondary' = 'primary') => ({
      backgroundColor: colors.bi.button[type === 'primary' ? 'primary' : 'secondary'],
      border: `1px solid ${colors.bi.button.border}`,
      color: type === 'primary' ? colors.base.white : colors.bi.primary,
      borderRadius: '6px',
      transition: colors.animations.duration.normal,
      ':hover': {
        backgroundColor: type === 'primary' 
          ? colors.bi.button.primaryHover 
          : colors.utils.withOpacity(colors.bi.button.secondary, 0.8)
      }
    })
  };
};

// 图表颜色hooks
export const useChartColors = () => {
  return {
    // 获取图表颜色
    primary: chartColors.primary,
    blues: chartColors.blues,
    gradients: chartColors.gradients,
    
    // 根据索引获取颜色
    get: (index: number, type: 'primary' | 'blues' = 'primary') => getChartColor(index, type),
    
    // 获取地图颜色
    map: chartColors.map,
    
    // 获取状态颜色
    status: chartColors.status,
    
    // 生成渐变色板
    generatePalette: (count: number, type: 'primary' | 'blues' = 'primary') => {
      const colors = chartColors[type];
      return Array.from({ length: count }, (_, i) => colors[i % colors.length]);
    }
  };
};

// CSS变量生成器（用于全局CSS注入）
export const generateCSSVariables = () => {
  return {
    // 基础色彩变量
    '--color-primary': baseColors.primary,
    '--color-secondary': baseColors.secondary,
    '--color-success': baseColors.success,
    '--color-warning': baseColors.warning,
    '--color-error': baseColors.error,
    
    // BI大屏变量
    '--bi-background': biScreenColors.background,
    '--bi-card-bg': biScreenColors.cardBg,
    '--bi-hover-bg': biScreenColors.hoverBg,
    '--bi-text-primary': biScreenColors.text.primary,
    '--bi-text-accent': biScreenColors.text.accent,
    '--bi-border-primary': biScreenColors.border.primary,
    
    // 动画变量
    '--animation-duration-fast': animations.duration.fast,
    '--animation-duration-normal': animations.duration.normal,
    '--animation-duration-slow': animations.duration.slow,
    '--animation-easing': animations.easing.easeInOut,
  };
};

// 样式工具函数
export const createStyleUtils = () => ({
  // 创建卡片样式
  card: (hover = true) => ({
    backgroundColor: biScreenColors.cardBg,
    border: `1px solid ${biScreenColors.border.muted}`,
    borderRadius: componentStyles.card.borderRadius,
    boxShadow: componentStyles.card.boxShadow,
    ...(hover && {
      transition: componentStyles.card.hover?.transition,
      '&:hover': {
        backgroundColor: biScreenColors.hoverBg,
        transform: componentStyles.card.hover?.transform
      }
    })
  }),
  
  // 创建按钮样式
  button: (variant: 'primary' | 'secondary' = 'primary') => ({
    backgroundColor: variant === 'primary' 
      ? biScreenColors.button.primary 
      : biScreenColors.button.secondary,
    border: `1px solid ${biScreenColors.button.border}`,
    color: variant === 'primary' ? baseColors.white : biScreenColors.primary,
    borderRadius: '6px',
    padding: '8px 16px',
    cursor: 'pointer',
    transition: animations.duration.normal,
    '&:hover': {
      backgroundColor: variant === 'primary'
        ? biScreenColors.button.primaryHover
        : `${biScreenColors.button.secondary}cc`
    }
  }),
  
  // 创建文本样式
  text: (variant: 'primary' | 'secondary' | 'accent' | 'muted' = 'primary') => ({
    color: biScreenColors.text[variant],
    fontWeight: variant === 'accent' ? 'bold' : 'normal'
  })
});

// 数据大屏主题颜色 Hook
export const useDataScreenColors = () => {
  const { themeMode } = useTheme();
  
  return {
    // 基础颜色
    primary: biScreenColors.primary,
    secondary: biScreenColors.secondary,
    background: biScreenColors.background,
    cardBg: biScreenColors.cardBg,
    hoverBg: biScreenColors.hoverBg,
    
    // 文字颜色
    textPrimary: biScreenColors.text.primary,
    textSecondary: biScreenColors.text.secondary,
    textAccent: biScreenColors.text.accent,
    textMuted: biScreenColors.text.muted,
    
    // 边框颜色
    borderPrimary: biScreenColors.border.primary,
    borderSecondary: biScreenColors.border.secondary,
    borderMuted: biScreenColors.border.muted,
    
    // 按钮颜色
    buttonPrimary: biScreenColors.button.primary,
    buttonPrimaryHover: biScreenColors.button.primaryHover,
    buttonSecondary: biScreenColors.button.secondary,
    buttonBorder: biScreenColors.button.border,
    
    // 排行榜颜色
    ranking: biScreenColors.ranking,
    
    // 渐变色
    gradientColors: biScreenColors.gradientColors,
    
    // 状态颜色
    status: chartColors.status,
    
    // 主题模式
    isDark: themeMode === 'dark',
  };
};

// 数据大屏样式类名 Hook
export const useDataScreenStyles = () => {
  const { themeMode } = useTheme();
  
  return {
    // 获取表格样式类名
    getTableClass: () => getDataScreenTableClass(themeMode === 'dark'),
    
    // 获取按钮样式类名
    getButtonClass: (type: 'primary' | 'secondary' = 'primary') => 
      getDataScreenButtonClass(type),
    
    // 获取动画样式类名
    getAnimationClass: (type: 'pulse' | 'blink' | 'rotate') => 
      getDataScreenAnimationClass(type),
    
    // 获取响应式文字大小
    getTextSize: (baseSize: number, screenWidth?: number) => 
      getDataScreenTextSize(baseSize, screenWidth),
    
    // 常用样式类名
    classes: {
      table: 'custom-table',
      button: {
        primary: 'custom-button',
        secondary: 'bi-button-secondary',
      },
      card: {
        base: 'bi-card',
        hover: 'hover-effect',
      },
      text: {
        primary: 'bi-text-primary',
        secondary: 'bi-text-secondary',
        accent: 'bi-text-accent',
        muted: 'bi-text-muted',
      },
      animation: {
        pulse: 'pulse-animation',
        blink: 'blink',
        rotate: 'rotate',
      },
    },
  };
};

// 数据大屏图表颜色 Hook
export const useDataScreenChartColors = () => {
  return {
    // 获取图表颜色
    getChartColor: (index: number, type: 'primary' | 'blues' = 'primary') => 
      getChartColor(index, type),
    
    // 获取渐变色
    getGradientColor: (index: number) => getGradientColor(index),
    
    // 获取状态颜色
    getStatusColor: (status: 'online' | 'offline' | 'warning' | 'normal') => 
      getStatusColor(status),
    
    // 获取排行榜颜色
    getRankingColor: (rank: number) => getRankingColor(rank),
    
    // 预定义的颜色数组
    primaryColors: chartColors.primary,
    blueColors: chartColors.blues,
    gradientColors: biScreenColors.gradientColors,
    statusColors: chartColors.status,
    rankingColors: biScreenColors.ranking,
  };
};

// 数据大屏响应式 Hook
export const useDataScreenResponsive = () => {
  const breakpoints = dataScreenStyles.breakpoints;
  
  const getResponsiveValue = <T>(values: {
    small?: T;
    medium?: T;
    large?: T;
    default: T;
  }): T => {
    if (typeof window === 'undefined') return values.default;
    
    const width = window.innerWidth;
    
    if (width <= breakpoints.small && values.small !== undefined) {
      return values.small;
    }
    if (width <= breakpoints.medium && values.medium !== undefined) {
      return values.medium;
    }
    if (width <= breakpoints.large && values.large !== undefined) {
      return values.large;
    }
    
    return values.default;
  };
  
  const isSmallScreen = () => {
    if (typeof window === 'undefined') return false;
    return window.innerWidth <= breakpoints.small;
  };
  
  const isMediumScreen = () => {
    if (typeof window === 'undefined') return false;
    return window.innerWidth <= breakpoints.medium;
  };
  
  const isLargeScreen = () => {
    if (typeof window === 'undefined') return false;
    return window.innerWidth <= breakpoints.large;
  };
  
  return {
    breakpoints,
    getResponsiveValue,
    isSmallScreen,
    isMediumScreen,
    isLargeScreen,
  };
};

// 数据大屏完整主题 Hook（集成所有功能）
export const useDataScreenTheme = () => {
  const colors = useDataScreenColors();
  const styles = useDataScreenStyles();
  const chartColors = useDataScreenChartColors();
  const responsive = useDataScreenResponsive();
  
  return {
    colors,
    styles,
    chartColors,
    responsive,
    
    // 常用样式配置
    tableConfig: {
      className: styles.getTableClass(),
      style: dataScreenStyles.table,
    },
    
    buttonConfig: {
      primary: {
        className: styles.getButtonClass('primary'),
        style: dataScreenStyles.button,
      },
      secondary: {
        className: styles.getButtonClass('secondary'),
      },
    },
    
    animationConfig: dataScreenStyles.animation,
  };
}; 